package me.learningandroid.ch3_2.sqlitedemo;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private static final String DB="todo.db";
    private static final int DBVER=1;

    private TodoDbHelper dbHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        dbHelper = new TodoDbHelper(this, DB, DBVER);

        Button addBtn = findViewById(R.id.button);
        EditText editTextContent = findViewById(R.id.editTextContent);
        RecyclerView recyclerView = findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        reloadList();

        addBtn.setOnClickListener(v -> {
            String content = editTextContent.getText().toString();
            ContentValues contentValues = new ContentValues();
            contentValues.put("content", content);
            contentValues.put("done", 0);
            //`db.insert` 封装了insert语句
            dbHelper.getWritableDatabase().insert("todo" /*into短语表明*/,
                    null /*nullContentHack，除非插入行全为null，不必设置*/,
                    contentValues /*values短语*/);
            reloadList();
        });
    }

    private void reloadList() {
        RecyclerView recyclerView = findViewById(R.id.recyclerView);

        List<TodoEntity> data = new ArrayList<>();
        // 查询时，只需要从`SQLiteOpenHelper`获取`ReadableDatabase`可读数据库。
        SQLiteDatabase dbr = dbHelper.getReadableDatabase();
        // 查询：`db.query`返回一个cursor
        Cursor cursor = dbr.query("todo" /*from短语中的表名*/,
                null /*select 短语中列名*/,
                null /*where 短语, 变量占位符为？*/,
                null /*where 短语中的变量*/,
                null /*groupBy 短语*/,
                null /*having短语*/,
                null /*order by 短语*/,
                null /*limit 短语*/
        );
        // `cursor`对象常用方法
        //   - `moveToFist` 移动cursor到第一行，同时判断cursor是否为空，如果cursor为空，返回false
        //   - `moveToNext` 移动cursor到下一行，如果没有返回false
        //   - `getInt`系列  获取行中的值
        if (cursor.moveToFirst()) {
            do {
                TodoEntity row=new TodoEntity();
                row.id = cursor.getInt(cursor.getColumnIndex("id"));
                row.content = cursor.getString(cursor.getColumnIndex("content"));
                row.done = cursor.getInt(cursor.getColumnIndex("done"));
                data.add(row);
            } while (cursor.moveToNext());
        }
        recyclerView.setAdapter(new TodoItemAdaptor(data, (v,isChecked)->{
            Integer id = (Integer) v.getTag();
            // 执行DML时，需要从`SQLiteOpenHelper`获取`WritableDatabase`可写数据库。
            SQLiteDatabase dbw=dbHelper.getWritableDatabase();
            ContentValues contentValues = new ContentValues();
            contentValues.put("done", isChecked?1:0);
                //`db.update` 封装了update语句
                dbw.update("todo" /*表名*/,
                        contentValues /*set语句*/,
                        "id=?" /*where语句*/,
                        new String[]{id.toString()} /*where语句中的值*/);
            reloadList();
        }, v->{
            Integer id = (Integer) v.getTag();
            // WritableDatabase
            SQLiteDatabase dbw=dbHelper.getWritableDatabase();
            // 演示如何使用transaction
            dbw.beginTransaction();
            try {
                //`db.delete` 封装了delete语句
                dbw.delete("todo"/*表名*/,
                        "id=?"/*where语句*/,
                        new String[]{id.toString()}/*where语句中的值*/);
                // `setTransactionSuccessful`组合`endTransaction`相当于commit。
                dbw.setTransactionSuccessful();
            } catch (Exception e) {
            } finally {
                // 如果有异常，单独调用`endTransaction`相当于rollback。
                dbw.endTransaction();
            }
            reloadList();
        }));
    }
}